import numpy as np

from util.util_ris_pattern import point_2_phase, phase_2_bit, phaseBit_2_deg, \
    phase_2_pattern_xyz_fft, phase_2_pattern, eps
from util.util_analysis_plane import get_peaks, get_peak_nth




# -------------------------------------------- 评价指标相关 ----------------------------------------------
# 比较 array1 相邻 array2 不相同的位数的矩阵
def compare_arrays(array1, array2):
    # 首先确保两个数组具有相同的形状
    if array1.shape != array2.shape:
        raise ValueError("两个数组的形状必须相同")
    # 使用 numpy.not_equal 比较两个数组
    # diff_coor = []
    # rows, cols = array1.shape
    # for i in range(rows):
    #     for j in range(cols):
    #         if array1[i][j] != array2[i][j]:
    #             diff_coor.append([i,j])
    # 结果是一个布尔数组，不同为 True，相同为 False
    comparison = np.not_equal(array1, array2)
    # 将布尔数组转换为整数数组，True 变为 1，False 变为 0
    result_matrix = comparison.astype(int)
    return result_matrix


# 计算psll和对应点的坐标: 归一化的 (具体实现)
def get_antenna_indicators_normalized_item(beam_num, pattern):
    psll, psll_coor = None, None   # PSLL 值, 坐标
    pg_list = None, None           # PG 列表=[值[x, y]] ps: 归一化的哦！
    pattern_dbw = 20 * np.log10(np.abs(pattern) / np.max(np.max(np.abs(pattern))) + eps)
    # 计算峰
    peaks = get_peaks(pattern_dbw)
    if peaks is not None:
        # 计算归一化的峰值增益 (Peak Gain)的坐标
        pg_list = peaks[: beam_num]
        # 计算归一化的最大旁瓣增益 (Peak Sidelobe Level, PSLL), 及其坐标
        peak_nth = get_peak_nth(peaks, beam_num)
        if peak_nth is not None:
            psll = peak_nth[0]
            psll_coor = peak_nth[1]
    return pg_list, psll, psll_coor, peaks

# 计算psll和对应点的坐标: 归一化的 (列表计算)
def get_antenna_indicators_normalized(beam_num, patterns):
    pg_list_list = []
    psll_list = []
    psll_coor_list = []
    for pattern in patterns:
        pg_list, psll, psll_coor, peaks = get_antenna_indicators_normalized_item(beam_num, pattern)
        pg_list_list.append(pg_list)
        psll_list.append(psll)
        psll_coor_list.append(psll_coor)
    return pg_list_list, psll_list, psll_coor_list


# 计算与前一个位置相比改变的码阵数量和
def get_phase_neighbor_diff(phaseBits):
    rows, cols = phaseBits[0].shape
    phaseBit_diff_list = [np.zeros((rows, cols))]                 # 记录码阵改变的位置
    phaseBit_diff_count_list = [0]           # 记录码阵改变数量和
    phaseBit_diff_count_percent_list = [0]   # 记录码阵改变数量和，占码阵数量的总百分比
    # 计算与前一个位置相比改变的码阵数量和
    for i in range(len(phaseBits)-1):
        phaseBit_diff_list.append(compare_arrays(phaseBits[i], phaseBits[i + 1]))
    # 计算每一步改变的码阵数量和，占码阵数量的总百分比
    for i in range(len(phaseBits) - 1):
        # 比较 phaseBit[i] 和 phaseBit[i+1] 的每一位，值不相同则 count 加 1
        count = np.sum(phaseBits[i] != phaseBits[i + 1])
        percentage = round((count / (rows * cols)) * 100, 4)
        phaseBit_diff_count_list.append(count)
        phaseBit_diff_count_percent_list.append(percentage)
    return phaseBit_diff_list, phaseBit_diff_count_list, phaseBit_diff_count_percent_list